<?php
/**
 *
 * @package avp
 * @version $Id: $
 * @copyright (c) 2006 Jan-Willem van Ganswijk, Stefan van Essen
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 */
define('IN_SCRIPT', 'TRUE'); //Voor de evil haxx0rz.
$root = '../';

include($root . 'includes/common.inc.php');
include($root . 'includes/lang.inc.php');
include($root . 'includes/session.class.php');
include($root . 'includes/admin.inc.php');
include($root . 'includes/template.class.php');

$session = new sessionWrapper();

$lang = read_langfiles('admin_common,admin_image');
$template = new template($CONFIG['theme']);
$template->add_var('active', 'images');

if (!$session->check_login()) {
    die(print_error($lang['ERROR_NEEDLOGIN'], 'login.php', true));
}

$action = addslashes($_GET['action']);

if ($action == 'list' || empty($action)) {
    $sort = addslashes($_GET['sort']);
    switch ($sort) {
        case 'name_down':
            $sort_clause = 'ORDER BY `imagename` DESC';
            break;
        case 'date_up':
            $sort_clause = 'ORDER BY `timestamp` ASC';
            break;
        case 'date_down':
            $sort_clause = 'ORDER BY `timestamp` DESC';
            break;
        case 'name_up':
        default:
            $sort_clause = 'ORDER BY `imagename` ASC';
            break;
    }
    /**
     * Pagination Logic
     */
    $total = $db->query_first("SELECT COUNT(`imageid`) AS total FROM `" . $db->get_table("images") . "`");
    $total = $total['total'];
    if ($total == 0) {
        $totalpages = 1;
    } else {
        $totalpages = ceil($total / $CONFIG['per_page']);
    }

    $page = addslashes($_GET['page']);
    if ($page > 1) {
        $limit_clause = 'LIMIT ' . (($page - 1) * $CONFIG['per_page']) . ',' . ($page * $CONFIG['per_page']);
    } else {
        $limit_clause = 'LIMIT 0,' . $CONFIG['per_page'];
        $page = 1;
    }

    $pagination = '';
    for($i = 1 ; $i <= $totalpages ; $i++) {
        if ($i == $page) {
            $pagination .= "<b>{$i}</b> ";
        } else {
            $pagination .= "<a href=\"{$_SERVER[PHP_SELF]}?page={$i}\">{$i}</a> ";
        }
    }

    $result = $db->query("SELECT * FROM `" . $db->get_table('images') . "` {$sort_clause} {$limit_clause}");

    while ($row = $db->fetch($result)) {
        $row['filename'] = "thumbnail.php?imageid=" . $row['imageid'] . "&imgsize=max";
        $template->append('images', $row);
    }
    $template->add_var('pagination', $pagination);
    $template->set_title($lang['TITLE_LIST_IMAGES']);
    $template->add_templates('admin_header,admin_image_list,admin_footer');
    $template->make_page();
    exit;
} elseif ($action == 'add') {
    if (isset($_GET['submit'])) {
        $file_ext = explode('.' , $_FILES['imagefile']['name']);
        $file_ext = strtolower($file_ext[count($file_ext)-1]);

        $db->query("INSERT INTO `" . $db->get_table("images") . "` (`timestamp`,`ext`)
			VALUES ('" . time() . "','{$file_ext}')");

        $id = $db->get_insert_id();

        $filename = $root . "images/image-" . $id . "." . $file_ext;

        if (move_uploaded_file($_FILES['imagefile']['tmp_name'], $filename)) {
            header("location: " . $_SERVER['PHP_SELF'] . "?action=edit&id={$id}");
        } else {
            $db->query("DELETE FROM `" . $db->get_table("images") . "` WHERE `imageid`='" . $id . "' LIMIT 1");

            print_error($lang['ERROR_UPLOAD'], $_SERVER['PHP_SELF']);
        }
        exit;
    }
    $template->set_title($lang['TITLE_ADD_IMAGE']);

    $template->add_templates('admin_header,admin_image_add,admin_footer');
    $template->make_page();
} elseif ($action == 'edit') {
    $id = addslashes($_GET['id']);
    if ($id < 0 || !isset($_GET['id'])) {
        print_error($lang['ERROR_NOID'], $_SERVER['PHP_SELF']);
        exit;
    }
    if (isset($_GET['submit'])) {
        $passthru = (int)$_POST['passthru'];
        if ($passthru != 0 && $passthru != 1) {
            $passthru = 0;
        }
        $db->query("UPDATE`" . $db->get_table("images") . "` SET
					`imagename`='" . addslashes($_POST['name']) . "',
					`passthru`=" . $passthru . "
					WHERE imageid='{$id}' LIMIT 1");

        print_message($lang['TITLE_EDIT_IMAGE'], $lang['MSG_EDITED'], $_SERVER['PHP_SELF']);
        exit;
    }
    $values = $db->query_first("SELECT * FROM `" . $db->get_table("images") . "` WHERE imageid='{$id}' LIMIT 1");

    $passtrhu_radios = array(1 => $lang['YES'], 0 => $lang['NO']);

    $template->set_title($lang['TITLE_EDIT_IMAGE']);
    $template->add_vars(array('values' => $values, 'passtrhu_radios' => $passtrhu_radios));
    $template->add_templates('admin_header,admin_image_edit,admin_footer');
    $template->make_page();
} elseif ($action == 'delete') {
    $id = addslashes($_GET['id']);
    if ($id < 0 || !isset($_GET['id'])) {
        print_error($lang['ERROR_NOID'], $_SERVER['PHP_SELF']);
        exit;
    } elseif ($id == $CONFIG['not_allowed_image']) {
        print_error($lang['ERROR_NODELETE_NOTALLOWEDIMG'], $_SERVER['PHP_SELF']);
        exit;
    } elseif ($id == $CONFIG['not_found_image']) {
        print_error($lang['ERROR_NODELETE_NOTFOUNDIMG'], $_SERVER['PHP_SELF']);
        exit;
    } elseif (isset($_GET['submit'])) {
        $row = $db->query_first("SELECT * FROM `" . $db->get_table('images') . "` WHERE imageid='{$id}' LIMIT 1");
        if (is_file($root . "images/image-" . $row["imageid"] . "." . $row["ext"])) {
            unlink($root . "images/image-" . $row["imageid"] . "." . $row["ext"]);
        }
        $db->query("DELETE FROM `" . $db->get_table('images') . "` WHERE imageid='{$id}' LIMIT 1");
        $db->query("DELETE FROM `" . $db->get_table('sets') . "` WHERE imageid='{$id}' LIMIT 1");

        print_message($lang['TITLE_DELETE_IMAGE'], $lang['MSG_DELETED'], $_SERVER['PHP_SELF']);
        exit;
    }

    print_confirmbox($_SERVER['PHP_SELF'] . "?action=delete&submit&id=" . $id, $_SERVER['PHP_SELF']);
    exit;
}

?>
